#pragma once

#include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>
#include "log.hpp"
using namespace std;

namespace client
{
    enum
    {
        Usage_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR,
        OPEN_ERR
    };
    class tcpclient
    {
    public:
        tcpclient(const string &ip, const uint16_t &port)
            : _serverip(ip), _serverport(port), _sock(-1)
        {
        }
        void initclient()
        {
            // 1、创建套接字
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                cout << "create socket error" << endl;
                exit(2);
            }

            // 2、tcp客户端要bind，但是不需要显示bind，由os自动bind
            // 3、客户端不需要listen!
            // 4、客户端也不需要accept!

            // 5、客户端是要发起连接的！
        }
        void start()
        {
            // 5、发起连接
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            if (connect(_sock, (struct sockaddr *)&server, sizeof(server)) != 0)
            {
                cout << "socket connent error" << endl;
                exit(3);
            }
            else // 连接成功
            {
                string message;
                while (1)
                {

                    cout << "Enter#";
                    getline(cin, message);

                    write(_sock, message.c_str(), message.size());

                    char buff[1024];
                    int n = read(_sock, buff, sizeof(buff) - 1);
                    if (n > 0)
                    {
                        buff[n] = 0; // 当成字符串
                        cout << "server回显" << buff << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~tcpclient()
        {
            if (_sock >= 0)
                close(_sock);
        }

    private:
        int _sock;
        string _serverip;
        uint16_t _serverport;
    };
}